package org.jsbd.boss.task;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.zhexinit.proxy.domain.HttpContext;
import com.zhexinit.proxy.domain.HttpProxyLog;
import com.zhexinit.proxy.domain.ProxyHost;
import com.zhexinit.proxy.util.ProxyHostUtils;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * 咪咕apk下载
 * 
 * @author zbh
 * 
 */
public class MiguAPKDownLoadTask implements Runnable {

	private RedisClient redisClient;
	// 用于判断定时任务是否开启
	private final static String QUARTZ_FLAG_ON = "on";
	// 定时任务开关：默认为off
	private String quartzFlag = "on";

	private long time = 1000;

	private static int total = PropertiesUtil.getInt("MiguAPKDownLoadtotal", 100);
	public static final int SO_TIMEOUT = 5000;

	public static final int RETRY = 3;

	private static final int ONE_DAY = 60 * 60 * 24;

	public static final Logger LOGGER = LoggerFactory.getLogger(MiguAPKDownLoadTask.class);

	private static Random r = new Random();
	private static final String[] RELEASE = { "2.3.6", "4.0.4", "4.4.2", "4.2.1", "4.3", "4.4.4", "4.1.2", "4.1.1" };
	private static final String[] HSTYPE = { "vivo Y27", "SM-G5108", "HTC D816w", "MIU-H6", "gucci", "R823T",
			"R7Plusm", "HM NOTE 1LTETD", "SM-G3508I", "SM-G3508J", "R831T", "Lenovo A656", "SM-G9008V",
			"HUAWEI Y511-T00", "H30-U10", "Coolpad 5200S", "X905", "S39h", "Coolpad 5200", "ALE-TL00", "SHV-E210L",
			"CRAVE S1", "Lenovo A398t+", "S2", "GT-I8558", "HM 1S" };

	// "http://wap.cmread.com/tingmedia/apk/heTingShu_2.2.7_L0010088.apk";

	private static String[] params = { "P9980", "P9975", "P9974", "P9967", "P9965", "P9958", "P9953", "P9991", "P9989",
			"P9987", "P9941", "P9743", "P9742", "P9741", "P9740", "P9739", "P9738", "P9737", "P9736", "P9735", "P9734",
			"P9733", "P9732", "P9731", "P9730", "P9729", "P9728", "P9727", "P9726", "P9725", "P9724", "P9723", "P9722",
			"P9721", "P9720", "P9719", "P9718", "P9717", "P9716", "P9715", "P9714", "P9713", "P9712", "P9711", "P9710",
			"P9709", "P9708", "P9707", "P9706", "P9705", "P9704" };
	
	private static String[] urls = { "http://wap.dm.10086.cn/app/hdm/soft/Manshang_700005126.apk"};
	@Autowired
	private DelayExecuteBuffer<HttpProxyLog> zxHttpProxyLogBuffer;

	public void start() {
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		// 只有当定时任务为on的时候才会去执行业务逻辑
		if (QUARTZ_FLAG_ON.equalsIgnoreCase(quartzFlag)) {
			while (true) {
				for (String param : params) {
					Calendar cal = Calendar.getInstance();
					String date = df.format(cal.getTime());
					String miguapkdownloadcountkey = "MIGUAPKDOWNLOAD_TODAYSUCC_COUNT_"+param+"_" + date;
					Long counter = redisClient.getLong(miguapkdownloadcountkey);
					if (counter == null) {
						counter = 0L;
					}
					if (counter < total) {
						try {
						 String downloadurl = "http://extension.miguxue.com/interface/downloadConfirm.action?channel="+param+"&clientId=1063114460";
						 download(downloadurl);
						 counter = redisClient.incrementBy(miguapkdownloadcountkey, 1, ONE_DAY);
						 LOGGER.info("download, success,count:[{}]", counter);
						} catch (Exception e) {
							LOGGER.error("", e);
						}
						try {
							// logger.info("当前没有imsi有任务");
							Thread.sleep(5000);
						} catch (InterruptedException e) {
							LOGGER.error("", e);
						}

					}
				}
				
				for (String url : urls) {
					Calendar cal = Calendar.getInstance();
					String date = df.format(cal.getTime());
					String miguapkdownloadcountkey = "MIGUAPKDOWNLOAD_TODAYSUCC_COUNT_"+url+"_" + date;
					Long counter = redisClient.getLong(miguapkdownloadcountkey);
					if (counter == null) {
						counter = 0L;
					}
					if (counter < total) {
						try {
						 String downloadurl = url;
						 download(downloadurl);
						 counter = redisClient.incrementBy(miguapkdownloadcountkey, 1, ONE_DAY);
						 LOGGER.info("download, success,count:[{}]", counter);
						} catch (Exception e) {
							LOGGER.error("", e);
						}
						try {
							// logger.info("当前没有imsi有任务");
							Thread.sleep(5000);
						} catch (InterruptedException e) {
							LOGGER.error("", e);
						}

					}
				}
				
				try {
					// logger.info("今天已经执行了+total+");
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					LOGGER.error("", e);
				}
			}
		}
	}
	
	public  void download(String downloadurl){
		
		String release = getRelease();
		String hstype = getHstype();
		String build = getBuild();

		HttpContext httpContext = new HttpContext();
		httpContext.setOrderId(UUID.randomUUID().toString());
		httpContext.setProvinceId("-1");
		httpContext.setImsi(httpContext.getOrderId());
		httpContext.setBizType("MiguxinbaoAPKDownLoad");
		httpContext.setStep(0);
		HttpProxyLog httpProxyLog = new HttpProxyLog();
		httpProxyLog.setHttpContext(httpContext);
		httpProxyLog.setUrl(downloadurl);
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headerMap.put("Accept-Encoding", "gzip,deflate");
		headerMap.put("Accept-Language", "zh-CN,en-US;q=0.8");
		headerMap.put("Accept-Charset", "utf-8, iso-8859-1, utf-16, gb2312, gbk, *;q=0.7");
		headerMap.put("User-Agent", "Mozilla/5.0 (Linux; U; Android " + release + "; zh-cn; "
				+ hstype + " Build/" + build
				+ ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");

		httpProxyLog.setHeaderMap(headerMap);

		// byte[] body =
		// HttpProxyUtils.httpDownload(httpProxyLog,
		// zxHttpProxyLogBuffer, false);
		// FileUtil.writeBytes("d:/test.apk", body);
		httpDownload(httpProxyLog, zxHttpProxyLogBuffer, false);
	}

	public String getQuartzFlag() {
		return quartzFlag;
	}

	public void setQuartzFlag(String quartzFlag) {
		this.quartzFlag = quartzFlag;
	}

	public static String getQuartzFlagOn() {
		return QUARTZ_FLAG_ON;
	}

	public long getTime() {
		return time;
	}

	public void setTime(long time) {
		this.time = time;
	}

	public static boolean httpDownload(HttpProxyLog httpProxyLog, DelayExecuteBuffer<HttpProxyLog> httpProxyLogBuffer,
			boolean https) {
		HttpContext httpContext = httpProxyLog.getHttpContext();
		String provinceId = httpContext.getProvinceId();
		String imsi = httpContext.getImsi();
		ProxyHost proxyHost = ProxyHostUtils.getProxyHost(imsi, provinceId, 5, httpProxyLog.getHttpContext()
				.getBizType());
		httpProxyLog.setIpConnect(proxyHost.getIp());
		httpProxyLog.getHeaderMap().put("Ip", proxyHost.getIp());

		long t = System.currentTimeMillis();

		String url = httpProxyLog.getUrl();
		try {
			// 填写相关请求头信息和请求参数信息
			// client.executeMethod(httpGet);
			// InputStream in = httpGet.getResponseBodyAsStream();

			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost.getAddress(), proxyHost.getPort()));
			URLConnection conn = new URL(url).openConnection(proxy);

			String release = getRelease();
			String hstype = getHstype();
			String build = getBuild();

			conn.setRequestProperty("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
			conn.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8");
			conn.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, gb2312, gbk, *;q=0.7");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android " + release + "; zh-cn; " + hstype
					+ " Build/" + build + ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
			InputStream in = conn.getInputStream();
			//ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len = 0;
			if ((len = in.read(b)) > -1) {
				// out.write(b, 0, len);
				LOGGER.info("download success");
			}
			 //FileUtil.writeBytes("d:/"+UUID.randomUUID()+".apk", out.toByteArray());
			// httpGet.releaseConnection();
			in.close();
			// out.close();

		} catch (Exception e) {
			LOGGER.error("http 代理请求失败 [{}]", httpProxyLog, e);
			return false;
		} finally {
			long t1 = System.currentTimeMillis();
			httpProxyLog.setReadTime(t1 - t);
			httpProxyLogBuffer.add(httpProxyLog);
		}
		return true;
	}

	public static String getRelease() {
		return RELEASE[r.nextInt(RELEASE.length)];
	}

	public static String getHstype() {
		return HSTYPE[r.nextInt(HSTYPE.length)];
	}

	public static String getBuild() {
		return UUID.randomUUID().toString().substring(0, 6).toUpperCase();
	}

	public RedisClient getRedisClient() {
		return redisClient;
	}

	public void setRedisClient(RedisClient redisClient) {
		this.redisClient = redisClient;
	}

}
